import { defineStore } from "pinia";
import { ElMessage } from 'element-plus';

//引入数据类型
import type { adminLogin, GetClassListParams } from "@/api/admin/type";
//引入接口登录的接口
import { reqAdminLogin } from "@/api/admin";
import { REMOVE_TOKEN, GET_TOKEN, parseJwt } from "@/utils/token";
import { reqExportStudentScore, reqGetStudentsScore, reqExportGroupScore, reqAllowAndSetPro, reqGetGroupList, reqDeleteClass, reqCreateClass, reqGetClassList, reqAdminRegister, reqAdminForgetPassword, reqAdminUpdateInfo } from "@/api/admin";
import type { GetStudentsListParams, allowAndSetProDatePrams, getGroupsDatePrams, createClass, adminRegister, adminForgetPassword, adminUpdate } from "@/api/admin/type";
import { adminRoute } from "@/router/admin";

// 预处理菜单数据，确保它是数组形式
const processMenuRoutes = () => {
    console.log('Processing admin menu routes');
    console.log('Original adminRoute:', adminRoute);
    
    if (!adminRoute) {
        console.error('Admin route is undefined');
        return [];
    }
    
    if (Array.isArray(adminRoute)) {
        console.log('Admin route is already an array with length:', adminRoute.length);
        return adminRoute;
    } else {
        console.log('Admin route is not an array, converting to array');
        return [adminRoute];
    }
};

//创建管理员小仓库               小仓库的名字 AdminStore
let useAdminStore = defineStore('AdminStore', {
    //小仓库存储数据
    state: () => {
        const menuRoutes = processMenuRoutes();
        console.log('Final admin menuRoutes:', menuRoutes);
        
        return {
            token: GET_TOKEN(),//用户唯一标识
            menuRoutes, // 预处理的菜单路由
            userInfo: {
                adminUsername: '',
                adminEmail: ''
            },
            tableData: [] as Array<{
                classId: number;
                adminUsername: string;
                className: string;
                classStudentNumber: number;
                adminId: number;
            }>,
            page: { page: 1, pageSize: 10, total: 0 },
            groupTableData: [] as Array<{
                classId: number;
                adminUsername: string;
                className: string;
                classStudentNumber: number;
                adminId: number;
            }>,
            tableGroupsData: [] as Array<{
                groupId: number;
                studentId: number;
                groupName: string;
                groupProName: string;
                groupScore: number;
                groupIsAvailable: number;
                groupLeader: string;
                groupNotice: string | null;
                groupFinish: number;
                classId: number;
                giteeUrl: string;
            }>,
            tableStudentsData: [] as Array<{
                studentName: string;
                studentId: number;
                studentNumber: string;
                groupProName: string;
                groupScore: number;
                studentFinish: number;
                groupId: number
            }>
        }

    },
    //异步 逻辑的处理的地方
    actions: {
        async adminLogin(data: adminLogin) {
            console.log(data);
            let result = await reqAdminLogin(data);

            console.log("管理员登录的逻辑处理")
            console.log(this.menuRoutes)
            console.log(result)
            //登录成功 存储token
            if (result.code == 200) {

                //pinia仓库存储token
                this.token = result.data;
                //本地持久化存储
                localStorage.setItem("TOKEN", result.data);
                if (this.token != null) {
                    let claims = parseJwt(this.token);
                    this.userInfo.adminUsername = claims.adminUsername;
                    this.userInfo.adminEmail = claims.adminEmail;
                }
                else {
                    return Promise.reject(new Error("这个管理员未登录"));
                }

                return 'ok';
            }
            else {
                return Promise.reject(new Error(result.data));
            }
            //存储失败 返回错误信息
        },
        async adminRegister(data: adminRegister) {
            try {
                const result = await reqAdminRegister(data);

                console.log("管理员注册的逻辑处理");
                console.log(result);

                if (result.code === 200) {
                    //注册成功 弹出一个注册成功跳转登录页面
                    ElMessage.success('注册成功！');
                    return 'ok';
                } else {
                    return Promise.reject(new Error(result.message || "注册失败"));
                }
            } catch (error) {
                ElMessage.error('注册失败 请重试！');
                return Promise.reject(error);
            }
        },
        async adminForgetPassword(data: adminForgetPassword) {
            console.log(data);
            let result = await reqAdminForgetPassword(data);

            console.log("学生找回密码")
            console.log(result)
            //登录成功 存储token
            if (result.code == 200) {
                //找回密码成功 弹出一个找回成功跳转登录页面
                ElMessage.success('找回密码成功！');
                return 'ok';
            }
            else {
                //注册失败 
                ElMessage.error('找回密码失败 请核对后重实');

                return Promise.reject(new Error(result.data));
            }
            //存储失败 返回错误信息
        },
        async updateInfo(updateData: adminUpdate) {
            try {
                console.log("进入更新函数了吗？")
                // 假设你的API端点是 /api/students/update
                const response = await reqAdminUpdateInfo(updateData);
                if (response.code = 200) {
                    return 'ok';
                }
            } catch (error) {
                console.error("Failed to update student info", error);
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        async fetchTableData(data: GetClassListParams) {
            try {
                const response = await reqGetClassList(data); // 替换为你的后端API地址
                console.log(response);
                console.log(response.data.list);
                this.tableData = response.data.list; // 提取list数据
                this.page.total = response.data.total; // 提取total记录数
            } catch (error) {
                console.error("Error fetching the data", error);
            }
        },
        async addClass(data: createClass) {
            try {
                //获取adminId 和adminUsername并赋值给data
                if (this.token != null) {
                    let claims = parseJwt(this.token);
                    data.adminUsername = claims.adminUsername;
                    data.adminId = claims.adminId;
                }
                console.log(data);
                const response = await reqCreateClass(data);
                if (response.code == 200) {
                    return 'ok';
                }
            } catch (error) {
                console.error("Failed to update student info", error);
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        async deleteClass(classId: number) {
            try {

                console.log(classId);
                const response = await reqDeleteClass(classId);
                if (response.code == 200) {
                    return 'ok';
                }
            } catch (error) {
                console.error("Failed to update student info", error);
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        async fetchTableGroupsData(params: getGroupsDatePrams) {
            try {
                const response = await reqGetGroupList(params)
                if (response.code === 200) {
                    this.tableGroupsData = response.data.list; // 假设返回的数据结构包含 records 字段
                    this.page.total = response.data.total;
                } else {
                    console.error('Failed to fetch table data:', response.msg);
                }
            } catch (error) {
                console.error('Error fetching table data:', error);
            }
        },
        async allowAndSetPro(params: allowAndSetProDatePrams) {
            try {
                console.log(params);
                const response = await reqAllowAndSetPro(params)
                if (response.code === 200) {
                    ElMessage.success('小组打分立项修改成功');
                    return 'ok';
                } else {
                    ElMessage.error('小组打分立项修改失败');
                    console.error('Failed to fetch table data:', response.msg);
                }
            } catch (error) {
                console.error('Error fetching table data:', error);
            }
        },
        async exportGroups(params: string) {
            console.log(params);
            await reqExportGroupScore(params)

        },
        async fetchTableStudentsData(params: GetStudentsListParams) {
            console.log(params);

            try {
                const response = await reqGetStudentsScore(params)
                if (response.code === 200) {
                    this.tableStudentsData = response.data.list;
                } else {
                    console.error('Failed to fetch table data:', response.msg);
                }
            } catch (error) {
                console.error('Error fetching table data:', error);
            }
        },
        async exportStudentScore(params: string) {
            console.log(params);
            await reqExportStudentScore(params)

        },
        userLogout() {
            try {
                // 调用后端登出接口（如果有的话）

                // 清除本地存储中的Token
                REMOVE_TOKEN();

                // 重置store中的token和userInfo
                this.token = '';
                this.userInfo.adminUsername = '';
                this.userInfo.adminEmail = '';

                // 可选：清除其他相关状态
                this.tableData = [];
                this.page = { page: 1, pageSize: 10, total: 0 };
                this.groupTableData = [];
                this.tableGroupsData = [];
                this.tableStudentsData = [];


            } catch (error) {
                console.error('登出失败:', error);
                ElMessage.error('登出失败，请稍后再试');
            }
        }
    },
    getters: {}
})
export default useAdminStore

